<template>
  <div>
    <button type="button" v-on:click="selectFile()" class="btn btn-white btn-default btn-round">
      <i class="ace-icon fa fa-upload"></i>
      {{text}}
    </button>
    <input class="hidden" type="file" ref="file" v-on:change="uploadFile()" v-bind:id="inputId+'-input'">
  </div>
</template>

<script>
import Toast from "../../public/static/js/toast";
import Loading from "../../public/static/js/loading";
import Tool from "../../public/static/js/tool";

  export default {
    name: 'big-file',
    props: {
      text: {
        default: "上传大文件"
      },
      inputId: {
        default: "file-upload"
      },
      suffixs: {
        default: []
      },
      use: {
        default: ""
      },
      afterUpload: {
        type: Function,
        default: null
      },
    },
    data: function () {
      return {
        fileBase: `${process.env.VUE_APP_BASE_URL}/file`,
      }
    },
    methods: {
      uploadFile () {
        let _this = this;
        let formData = new window.FormData();
        let file = _this.$refs.file.files[0];

        // 判断文件格式
        let suffixs = _this.suffixs;
        let fileName = file.name;
        let suffix = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length).toLowerCase();
        let validateSuffix = false;
        for (let i = 0; i < suffixs.length; i++) {
          if (suffixs[i].toLowerCase() === suffix) {
            validateSuffix = true;
            break;
          }
        }
        if (!validateSuffix) {
          Toast.warning("文件格式不正确！只支持上传：" + suffixs.join(","));
          document.getElementById(_this.inputId + "-input").value=""
          return;
        }

        // 生成文件标识key
        console.log(file)
        let key = hex_md5(file.name + file.size + file.type + file.lastModified);
        let key10 = parseInt(key, 16)
        let key16 = Tool._10to62(key10)
        // 文件分片
        let shardSize = 20 * 1024 * 1024
        // 分片索引 从1开始
        let shardIndex = 1
        let size = file.size
        // 总片数
        let shardTotal = Math.ceil(size / shardSize)

        // key："file"必须和后端controller参数名一致
        formData.append('use', _this.use);
        formData.append('shardIndex', shardIndex)
        formData.append('shardSize', shardSize)
        formData.append('shardTotal', shardTotal)
        formData.append('name', file.name)
        formData.append('suffix', suffix)
        formData.append('size', size)
        formData.append('key', key16)

        _this.upload(formData, file)
      },

      upload(param, file) {
          console.log(file)
          let _this = this;
          let shardIndex = param.get("shardIndex")
          let shardTotal = param.get("shardTotal")
          let shardSize = param.get("shardSize")
          let shard = _this.getFileShard(shardIndex, shardSize, file);

          param.append('shard', shard)
          Loading.show()
          _this.$axios.post(`${_this.fileBase}/upload`, param).then((res)=>{
            Loading.hide()
            if(res.data.success) {
                // Toast.success(_this.text+"成功");
                if (shardIndex < shardTotal) {
                    // 继续上传分片
                    param.set("shardIndex", parseInt(param.get("shardIndex")) + 1)
                    this.upload(param, file)
                } else {
                    // 上传完毕
                    // _this.afterUpload(res);
                    $("#" + _this.inputId + "-input").val("");
                }
            } else {
                Toast.error(_this.text + '失败')
            }
        }).catch(() => {
            $("#" + _this.inputId + "-input").val("");
            Loading.hide()
            Toast.error('系统异常')
        });
      },

      getFileShard (shardIndex, shardSize, file) {
        let start = (shardIndex - 1) * shardSize;	//当前分片起始位置
        let end = Math.min(file.size, start + shardSize); //当前分片结束位置
        let fileShard = file.slice(start, end); //从文件中截取当前的分片数据
        return fileShard;
      },
      selectFile () {
        let _this = this;
        $("#" + _this.inputId + "-input").trigger("click");
      }
    }
  }
</script>
